package xyz.larkin.common.api.impl;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xyz.larkin.common.api.ZkService;

import java.util.List;

/**
 * Created by liujin on 2018/12/24.
 *
 * @description TODO
 */

@Service(value = "zkService")
public class ZkClient implements InitializingBean, DisposableBean, ZkService {
    private ZooKeeper zk;

    @Value("${zookeeper.url}")
    private String zkUrl;
    @Override
    public void afterPropertiesSet() throws Exception {
        zk = new ZooKeeper(zkUrl, 500000, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {
                //dosomething
            }
        });
    }

    @Override
    public String createNode(String nodePath, String data) throws KeeperException, InterruptedException {
        //创建一个节点root，数据是mydata,不进行ACL权限控制，节点为永久性的(即客户端shutdown了也不会消失)
        return zk.create(nodePath, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Override
    public List<String> getChildrenList(String path) throws KeeperException, InterruptedException {
        //取得/root节点下的子节点名称,返回List<String>
        return zk.getChildren(path, true);
    }

    @Override
    public String getData(String path) throws KeeperException, InterruptedException {
        //取得/root/childone节点下的数据,返回byte[]
        return new String(zk.getData(path, true, null));
    }

    @Override
    public Stat setData(String path, String data) throws KeeperException, InterruptedException {

        //修改节点/root/childone下的数据，第三个参数为版本，如果是-1，那会无视被修改的数据版本，直接改掉
        return zk.setData(path, data.getBytes(), -1);
    }

    @Override
    public void deleteNode(String path) throws KeeperException, InterruptedException {
        //删除/root/childone这个节点，第二个参数为版本，－1的话直接删除，无视版本
        zk.delete(path, -1);
    }

    @Override
    public void destroy() throws Exception {
        //关闭session
        zk.close();
    }
}
